import Vue from 'vue'
import App from './App.vue'
import routes from './router'
import store from './store'
import BaseUI,{BaseUtil} from '@zkwq/business';
import '@zkwq/business/dist/index.min.css';
import VueRouter from 'vue-router'
import AppMixin from './mixins'
import {STORE,CACHE_KEY} from '@/constants'
import client from 'webpack-theme-color-replacer/client'
import getElementUISeries from 'webpack-theme-color-replacer/forElementUI/getElementUISeries'
import themeConfig from './theme'
import {getUrlParam,getAccessToken,toLogin,MAGAZINE} from './service/login'
import { LoginPlatform } from './service/user';
import { GetMagazineIdByDomain } from './service/magazine';
import {BounceLoading} from "@zkwq/business";
Vue.config.productionTip = false
Vue.use(VueRouter);
Vue.use(BaseUI);
Vue.component("BounceLoading", BounceLoading);
let router = null
let instance = null

async function render(props = {}) {
  let { container, clientType, user, theme,topic,topicId,oauthUri,appid } = props;
  router = new VueRouter({
    base: window.__POWERED_BY_QIANKUN__ ? clientType : '/',
    routes,
    mode: 'history',
    strict: process.env.NODE_ENV !== 'production',
    scrollBehavior (to, from, savedPosition) {
      if (savedPosition) {
        return savedPosition
      } else {
        if (from.meta.keepAlive) {
          from.meta.savedPosition = document.body.scrollTop
        }
        return { x: 0, y: to.meta.savedPosition || 0 }
      }
    }
  })
  store.commit(STORE.SET_PROPS,{
    user,topic,topicId,oauthUri,appid,clientType,theme
  })
  Vue.mixin(AppMixin)
  instance = new Vue({
    router,
    store,
    render: h => h(App)
  }).$mount(container ? container.querySelector('#app') : '#app')
  if (theme) {
    client.changer.changeColor({
      newColors: themeConfig.getThemeColors(theme.primaryColor ? theme.primaryColor : themeConfig.themeColor, getElementUISeries, client.varyColor, []),
      appendToEl: theme.container
    }, Promise).then(() => {})
  }
}

// 独立运行时
if (!window.__POWERED_BY_QIANKUN__) {
  console.log('Navigator App Bootstraped Alone')

  if(getUrlParam('code') && getUrlParam('state')){
    getAccessToken(getUrlParam('code'),(e) => {
        LoginPlatform(e).then(data => {
          if(data.code == 0){
            let info = data.data;
            BaseUtil.setStorage(CACHE_KEY.USER,info.user)
            BaseUtil.setStorage(CACHE_KEY.PERMISSION,info.permissionList || [])
            BaseUtil.setStorage(CACHE_KEY.TOKEN,info.tokenInfo)
            BaseUtil.setStorage(CACHE_KEY.ROLE,info.roleList || [])
            if(BaseUtil.getStorage(CACHE_KEY.LOGIN_TO_URL)){
                location.href = BaseUtil.getStorage(CACHE_KEY.LOGIN_TO_URL);
                BaseUtil.removeStorage(CACHE_KEY.LOGIN_TO_URL)
            }else{
                location.href = '/'
            }
          }
          // else if(data.code == -403){
          //   location.href = '/disabled'
          // }
        }).catch(data => {
            location.href = '/'
        })
    },(e) => {
      toLogin()
    })
  }else{

    console.log(location.hostname)
    console.log("magazine=="+JSON.stringify(MAGAZINE))
    // let domain = location.hostname.split(".")[0];
    // domain = "testyundian"
    // console.log("domain=="+domain)
    // let magazize = ""
    // try{
    //   let result = await GetMagazineIdByDomain(domain);
    //   if (result.code == 0 && result.data) {
    //     magazize = result.data
    //   }
    // }catch(e){

    // }
    store.commit(STORE.SET_MAGAZINE,MAGAZINE)
    let administrator = null;
    if(BaseUtil.getStorage(CACHE_KEY.USER)){
      administrator = BaseUtil.getStorage(CACHE_KEY.USER)
    }
    render({
      clientType:'/',
      user: administrator,
      topicId: '8352ec9f49a1e968c653e95ee9d71f73',
      theme:{
        primaryColor:'#2973D7'
      }
    })
  }
  
}

export async function bootstrap() {
  console.log('Dataset App Bootstraped');
}
export async function mount(props) {
  props.onGlobalStateChange((state, prev) => {
    // state: 变更后的状态; prev 变更前的状态
    if (Object.keys(state).length > 0) {
      props = { ...props, ...state }
      if (!props.await) {
        // console.log(props)
        render(props)
      }
    }
  });
  if (!props.await) {
    render(props)
  }
}
export async function unmount() {
  instance.$destroy()
  instance.$el.innerHTML = ''
  instance = null
  router = null
}
